import axios from 'axios';
import store from '../redux/store';

//axios.defaults.baseURL = 'http://localhost:5000';// 基地址
axios.defaults.baseURL = '';
// 请求拦截器
axios.interceptors.request.use(
    //显示Loading
    config => {
        //改变state 唯一的方法就是通过action来 触发 分发器Dispatcher
        store.dispatch({
            type: 'change_loading',
            payload: true
        });

        return config;
    },
    err => {
        return Promise.reject(err);
    }
);
// 响应拦截器
axios.interceptors.response.use(
    response => {
        //隐藏Loading
        store.dispatch({
            type: 'change_loading',
            payload: false
        });
        // console.log(response);
        return response;
    },
    err => {
        store.dispatch({
            type: 'change_loading',
            payload: false
        });
        
        return Promise.reject(err);
    }
);

export function post (url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, params).then(
            (response) => {
                resolve(response);
            },
            (err) => {
                reject(err);
            }
        )
        .catch((error) => {
            reject(error);
        })
    });
}

export function get (url, params) {
    return new Promise((resolve,reject) => {
        axios.get(url, {
            params:params
        }).then(
            (response) => {
                resolve(response);
            },
            (err) => {
                reject(err);
            }
        )
        .catch((error) => {
            reject(error);
        });
    });
}

export function patch (url, params) {
    return new Promise((resolve, reject) => {
        axios.patch(url, params).then(
            (response) => {
                resolve(response);
            },
            (err) => {
                reject(err);
            }
        )
        .catch((error) => {
            reject(error);
        })
    });
}

export function del (url) {
    return new Promise((resolve,reject) => {
        axios.delete(url).then(
            (response) => {
                resolve(response);
            },
            (err) => {
                reject(err);
            }
        )
        .catch((error) => {
            reject(error);
        })
    })
}
